import { Word, UserProgress } from '../models/word';
import StorageService from './storageService';
import SpacedRepetitionService from './spacedRepetitionService';

class WordService {
  private static instance: WordService;

  private constructor() {}

  static getInstance(): WordService {
    if (!WordService.instance) {
      WordService.instance = new WordService();
    }
    return WordService.instance;
  }

  /**
   * 初始化单词库
   */
  async initializeWords(): Promise<void> {
    const words = await StorageService.getWords();
    if (words.length === 0) {
      // 添加示例单词数据
      const sampleWords: Word[] = [
        {
          id: '1',
          word: 'abandon',
          phonetic: '/əˈbændən/',
          translation: '放弃，抛弃',
          example: 'He abandoned his car in the snow.',
          exampleTranslation: '他把车丢在雪地里。',
          category: 'CET-4',
          difficulty: 0,
          nextReviewDate: new Date(),
          reviewCount: 0,
          correctCount: 0,
          lastReviewed: null
        },
        {
          id: '2',
          word: 'benefit',
          phonetic: '/ˈbenɪfɪt/',
          translation: '利益，好处',
          example: 'The new policy will benefit everyone.',
          exampleTranslation: '新政策将使每个人受益。',
          category: 'CET-4',
          difficulty: 0,
          nextReviewDate: new Date(),
          reviewCount: 0,
          correctCount: 0,
          lastReviewed: null
        }
      ];
      await StorageService.saveWords(sampleWords);
    }
  }

  /**
   * 获取今日学习计划
   */
  async getTodaysStudyPlan(): Promise<Word[]> {
    const words = await StorageService.getWords();
    const progress = await StorageService.getUserProgress();

    // 获取需要复习的单词
    const wordsToReview = SpacedRepetitionService.getWordsToReview(words);

    // 获取新单词（根据每日目标）
    const newWordsNeeded = Math.max(0, progress.dailyGoal - progress.studiedToday);
    const newWords = SpacedRepetitionService.getNewWords(words, newWordsNeeded);

    return [...wordsToReview, ...newWords];
  }

  /**
   * 处理单词学习结果
   * @param wordId 单词ID
   * @param isCorrect 是否正确
   */
  async processWordResult(wordId: string, isCorrect: boolean): Promise<void> {
    const words = await StorageService.getWords();
    const progress = await StorageService.getUserProgress();

    const wordIndex = words.findIndex(w => w.id === wordId);
    if (wordIndex !== -1) {
      // 更新单词进度
      words[wordIndex] = SpacedRepetitionService.updateWordSchedule(words[wordIndex], isCorrect);

      // 更新用户进度
      if (isCorrect && words[wordIndex].difficulty >= 5) {
        // 单词掌握
        if (!progress.masteredWords.includes(wordId)) {
          progress.masteredWords.push(wordId);
        }
        progress.learningWords = progress.learningWords.filter(id => id !== wordId);
      } else if (!progress.learningWords.includes(wordId)) {
        // 添加到学习中列表
        progress.learningWords.push(wordId);
      }

      // 更新今日学习计数
      if (words[wordIndex].reviewCount === 1) { // 第一次学习
        progress.studiedToday += 1;
      }

      // 保存数据
      await StorageService.saveWords(words);
      await StorageService.saveUserProgress(progress);
    }
  }

  /**
   * 获取单词统计信息
   */
  async getStatistics(): Promise<{
    totalWords: number;
    masteredWords: number;
    learningWords: number;
    todayStudied: number;
    streak: number;
  }> {
    const words = await StorageService.getWords();
    const progress = await StorageService.getUserProgress();

    return {
      totalWords: words.length,
      masteredWords: progress.masteredWords.length,
      learningWords: progress.learningWords.length,
      todayStudied: progress.studiedToday,
      streak: progress.streak
    };
  }
}

export default WordService.getInstance();
